/**
 * Created by mooshroom on 2015/3/5.
 */

define('MDEditor', function () {
    return MDEditor = avalon.define({
        $id: 'MDEditor',
        md:"",
        ready: function () {
            MDEditor.toWrite();//切换为专注书写模式
            MDEditor.toRead();//切换为纯净阅读模式
            MDEditor.toBoth();//切换为实时预览模式
            MDEditor.autoHeight();//自适应高度
            MDEditor.doubleScroll();//实时预览双滚动
            require(["marked", "prettify"], function () {
                MDEditor.markdownConfig();
                prettyPrint();
                console.log("【markdown编辑器模块加载完成！】");
                MDEditor.trs();
            });
            avalon.scan();
        },
        markdownConfig: function () {

            marked.setOptions({
                renderer: new marked.Renderer(),
                gfm: true,
                tables: true,
                breaks: false,
                pedantic: false,
                sanitize: true,
                smartLists: true,
                smartypants: false
            });



        },
        //编译动作
        trs:function(){
            //var word = $("#doc-input").html().replace(/(<br>)|(<div>)|(<\/div>)/g,'\r\n').replace(/&nbsp;/g,' ');
            //var word = $("#doc-main").val();

            //console.log(word);
            document.getElementById('doc-show').innerHTML = marked(MDEditor.md);
            document.getElementById('read-only').innerHTML = marked(MDEditor.md);
            prettyPrint();
        },

        //编辑窗口动作
        toWrite: function () {
                $("#doc-show-tool").show();
                $(".doc-layout").removeClass("col-sm-6").addClass("col-sm-12");           //.doc-layout class变为col-sm-12
                $("#doc-show-layout").fadeOut();
                $("#doc-main-layout").fadeIn();
                //变形完成
                $("#doc-show").show();
                $("#read-only").hide();

                MDEditor.autoHeight()

        },
        toRead: function () {

                $(".doc-layout").removeClass("col-sm-6 col-sm-12").addClass("col-sm-12");           //.doc-layout class变为col-sm-12
                $("#doc-main-layout").fadeOut();
                $("#doc-show-layout").fadeIn();
                $("#doc-show").hide();
                $("#doc-show-tool").hide();
                $("#read-only").show();
                $('.doc-layout').css('height', 'auto')


                //变形完成

        },
        toBoth: function () {
                $("#read-only").hide();
                $("#doc-show").show();
                $("#nav-read").fadeOut();                                                  //#nav-both  class添加 hidden
                $("#nav-write").fadeOut();
                $(".doc-layout").removeClass("col-sm-6 col-sm-12").addClass("col-sm-6");           //.doc-layout class变为col-sm-12
                $("#doc-main-layout").fadeIn();
                $("#doc-show-layout").fadeIn();                                         //#doc-show-layout class添加hidden
                $("#nav-both").fadeIn();                                                //#nav-write class 去除hidden


                $("#doc-main-tool").find(".to-write").show();
                $("#doc-show-tool").find(".to-read").show();
                //变形完成
                MDEditor.autoHeight()

        },
        autoHeight: function () {
            var adaptHeight = function () {
                var x = $(window).height();
                $('.doc-layout').css('height', (x - 90) + 'px');
            };
            adaptHeight();
            $(window).resize(function () {
                adaptHeight();
            });

        },
        //2014年最吊代码：
        doubleScroll: function () {
            $(".live-sroll").hover(function () {
                $(this).on("scroll", function () {
                    //得到要跟随滚动的ID值
                    //元素获取
                    var thisId = $(this).attr('id');
                    var otherId = thisId == "doc-show" ? "doc-main" : "doc-show";
                    //参数获取
                    var sh1 = document.getElementById(thisId).scrollHeight;
                    var st1 = $("#" + thisId).scrollTop();
                    var sh2 = document.getElementById(otherId).scrollHeight;
                    var h1 = $("#" + thisId).height();
                    var h2 = $("#" + otherId).height();
                    //跟随滚动公式
                    // 实际运动高度
                    //var l1 = (sh1 - h1);
                    //var l2 = (sh2 - h2);
                    //文本运动高度之比与实际运动高度之比相等
                    var st2 = st1 / (sh1 - h1) * (sh2 - h2);
                    //动作执行
                    $("#" + otherId).scrollTop(st2);
                });
            }, function () {
                $(this).off("scroll");
            });


        },
//        插入内容模块

        insert: function (f1,f2,n1,n2) {
            var textarea = document.getElementById("doc-main");
            var start=textarea.selectionStart;//获取光标所在位置对应的文本节点
            var end=textarea.selectionEnd;
            var l=MDEditor.md.length;//获取整个文本总长度

            //插入指定的东西
            var t1=MDEditor.md.slice(0,start);
            var t=MDEditor.md.slice(start,end);
            var t2=MDEditor.md.slice(end,l);
            var afterMd=t1+f1+t+f2+t2  ;
            MDEditor.md=afterMd;

            //文本域获取焦点并且选中制定的文本
            textarea.focus();
            textarea.setSelectionRange(start+n1,end+n1+n2);

            //执行编译
            MDEditor.trs();
            console.log()


        },
        //快捷键

        //粗体
        bold:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("** 加粗的文字"," **",3,5)
            }
            else{
                MDEditor.insert("** "," **",3,0)
            }

        },
        //斜体
        Italic:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("*** 倾斜的文字"," ***",4,5)
            }
            else{
                MDEditor.insert("*** "," ***",4,0)
            }

        },
        //插入连接
        link:"",
        links:function(){
            $('#links').modal('hide');
            if(MDEditor.link==""){
                MDEditor.link="输入连接地址";
            }
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("[输入连接描述","]("+MDEditor.link+")",1,6)
            }
            else{
                MDEditor.insert("[","]("+MDEditor.link+")",1,0)
            }

            MDEditor.link="";

        },
        //段落引用
        quote:function(){
            MDEditor.insert("\r\n> ","",3,0)
        },
        //插入代码
        code:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("```输入代码语言\r\n输入代码","\r\n ```",3,6)
            }
            else{
                MDEditor.insert("```输入代码语言\r\n","\r\n ```",3,6)
            }

        },
        //插入图片
        img:function(){

        },
        //插入有序列表
        ol:function(){
            MDEditor.insert("\r\n1. ","",5,0)
        },
        //插入无序列表
        ul:function(){
            MDEditor.insert("\r\n*  ","",5,0)
        },
        //插入标题h1
        h1:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("\r\n# 标题1"," #",3,3)
            }
            else{
                MDEditor.insert("\r\n# "," #",3,0)
            }
        },
        //插入标题h2
        h2:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("\r\n## 标题2"," ##",4,3)
            }
            else{
                MDEditor.insert("\r\n## "," ##",4,0)
            }
        },
        //插入标题h3
        h3:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("\r\n### 标题3"," ###",5,3)
            }
            else{
                MDEditor.insert("\r\n### "," ###",6,0)
            }
        },
        //插入标题h4
        h4:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("\r\n#### 标题4"," ####",6,3)
            }
            else{
                MDEditor.insert("\r\n#### "," ####",6,0)
            }
        },
        //插入标题h5
        h5:function(){
            var textarea = document.getElementById("doc-main");
            if(textarea.selectionStart==textarea.selectionEnd){
                MDEditor.insert("\r\n##### 标题5"," #####",7,3)
            }
            else{
                MDEditor.insert("\r\n##### "," #####",7,0)
            }
        },

        //插入分割线
        divider:function(){
            MDEditor.insert("","\r\n---\r\n",7,0)
        },

        //分段落
        paragraph:function(){
            MDEditor.insert("\r\n\r\n","",2,0)
        }
    })
})
